import path from 'path'
import fs from 'fs'

export default function autoExport(options = {}) {
    const config = {
        watchDir: 'src/apis',
        outputFile: 'index.js',
    }
    
    Object.assign(config,options)
    
    return {
        name: 'auto-export',
        configureServer(server) {
            generateIndex(config)
            server.watcher.on('all', (event, filePath) => {
                const fullWatchPath = path.join(process.cwd(), config.watchDir)
                if (filePath.startsWith(fullWatchPath) && event !== 'change') {
                    generateIndex(config)
                }
            })
        },
        buildStart() {
            generateIndex(config)
        }
    }
}

function generateIndex(config) {
    try {
        const generatePath = path.resolve(process.cwd(), config.watchDir)
        const indexPath = path.join(generatePath, config.outputFile)
        
        if (!fs.existsSync(generatePath)) {
            console.warn(`⚠️ Directory ${config.watchDir} not exists, skip generating`)
            return
        }
        
        const files = fs.readdirSync(generatePath)
        .filter(file => file.endsWith('.js') && file !== config.outputFile)
        .map(file => path.basename(file, '.js'))
        
        const imports = files
        .map(name => `import ${name} from './${name}'`)
        .join('\n')
        
        const exports = `export default {\n\t${files.join(',\n\t')}\n}`
        
        const content = `${imports}\n\n${exports}\n`
        
        if (!fs.existsSync(indexPath) || fs.readFileSync(indexPath, 'utf8') !== content) {
            fs.writeFileSync(indexPath, content)
            console.log(`📦 Auto-generated ${path.relative(process.cwd(), indexPath)}`)
        }
    } catch (error) {
        console.error('🔴 Failed to generate index:', error)
    }
}